<template>
	<view class="page" ref="page">
		<!-- 搜索 -->
		<view class="search-index">
			<!-- #ifndef H5 -->
				<view class="icon" @click="onCode">
					<text class="iconfont ">&#xe60d;</text>
				</view> 
			<!-- #endif -->
			<!-- #ifdef  H5 -->
			<view class="icon" @click="onPayCode">
				<text class="iconfont icon-fukuanma">&#xe60c;</text>
			</view>
			<!-- #endif -->
			<view class="search" >
				<view class="iconfont "> &#xe60c;</view>
				<input type="text" v-model="search_name" @blur="onSearch()" placeholder="输入搜索内容" />
			</view>
			<view  class="search-btn" @tap="onSearch()">
				搜索
			</view>
			<view :class="is_history?'history':'nohistory' " @tap="searchHistory">
				历史采购
			</view>
		<!-- 	<view class="icon">
				<text class="iconfont "></text>
			</view> -->
		</view>
		<!-- <view class="history">
			历史采购
		</view> -->
		<!-- <view>{{data.property}}</view> -->
		<!-- 分类数据 -->
		<view class="property-one">
			
			<view :class="property_id==item.id?'temp checked':'temp ' " v-for="(item,index) in data.property"  @tap="checkProperty(item,index)" :key="index" >
				<view class="">
					<image :src="item.cover_image "></image>
				</view>	
				<view class="txt">
					<text>{{item.name}}</text>
				</view>	
			</view>
		</view>
		<view class="classify-data" :style="'height:'+height+'px'">
			
			<view class="classify-one">
				<scroll-view scroll-y class="classify-list">
					<view :class=" activity_index==index?'list action':'list' " v-for="item,index in data.activity" @tap.stop="checkActivity(item,index)">	
							<text>{{item.name}}</text>
					</view>
					<view :class="property_value_id==v.id?'list action':'list ' " v-for="(v,index) in data.property[checkIndex].sub"  @tap.stop="checkPropertyValue(v.id)" :key="index" >
						<text>{{v.name}}</text>
					</view>
					<view style="height: 50rpx;"></view>
				</scroll-view>
				
			</view>
			<view class="product">
				<!-- <view class="sorter-box">
					<view class="sorter-price">
						<view>
							价格
						</view>
						<view>
							<view class="txt">
								<text class="iconfont">&#xe631;</text>
							</view>
							<view class="txt">
								<text class="iconfont">&#xe632;</text>
							</view>
						</view>
					</view>
					<view>
						筛选
					</view>
				</view> -->
				<!-- bindscrolltolower 滚动触底 触发 好像是要与methods 同级才行 ，写getProduct没用 -->
				<scroll-view scroll-y 	bindscrolltolower="onReachBottom"  class="product-scroll">
					<view class="product-temp" v-for="item in data.productList" :key="item.id" @tap="toDetail(item)">
						<view class="img">
							<image :src="item.cover_image"></image>
						</view>
						<view class="content">
							<view class="title">{{item.name}}</view>
							<!-- <view class="label-box">
								<view class="label">
									{{item.batch_start_num||2}}件起批
								</view>
							</view> -->
							<view class="add-box">
								<view class="price"><span>￥</span>{{item.price}}</view>
								<view class="add"   @tap.stop="checkNorms(item)">
									选规格
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<!-- <view class="classify-two-three">
				<scroll-view scroll-y class="scroll">
				
						<view class="classify-three">
							<view class="list"  v-for="(v,index) in data.property[checkIndex].sub" :key="index" @tap="checkPropertyValue(v.id)">
								<image :src="v.cover_image "></image>
								<text>{{v.name}}</text>
							</view>
							
						</view>
					
				</scroll-view>
			</view> -->
		</view>
		
		<view class="batch-box">
			<view class="tip"  @tap.stop="showCard"> 有0种商品不符合下单要求，<span>点击查看详细</span></view>
			<view class="batch-temp">
				<view class="batch-price">
					<view class="img">
						<image :src="OSS_HOST+'img/batchCard.png'"></image>
					</view>
					<view class="item-price">
						<view class="item-price-box" @tap.stop="showCard">
							<span class="price"><text class="more">￥</text>{{amount}}</span> 
							<span class="detail">明细<text class="iconfont up">&#xe620;</text></span>
						</view>
						<view class="item-price-fee">
							 配送费：<span>￥{{delive_fee}}</span>
						</view>
						<view class="number">
							共{{product_type_num}}种{{product_num}}个商品
						</view>
					</view>
					<!-- <view class="num">
						1
					</view> -->
					
				</view>
				<view class="btn">
					<view class='btn-submit' @tap = "pay()">去结算</view>
					
				</view>
				
			</view>
			
		</view>
		<!-- tabbar -->
		<!-- <TabBar :tabBarShow="1"></TabBar> -->
		<!-- 选规格方式 -->
		<uni-popup ref="checkVenue" type="bottom" custom="true" >
			
			<view class="select-box">
				<view class="close" @tap="$refs['checkVenue'].close()" ><img src="http://api.xingdongty.com/uploader/upload/202207/13/2022071310570162ce347db2881.png" alt="" ></view>
				<view class="content">
					<view class="goods-box">
						<view class="img-item">
							<image :src="norms_cover_image" mode="aspectFit"></image>
						</view>
						<view class="price-item">
							<view class="price"><text>￥</text>  {{price}}</view>
							<view class='cost'>￥{{cost}}</view>
						</view>
					</view>
					<!-- <view class="title">
						{{data.detail.name}}
					</view>	
					<view class="price">
						￥{{price}}
					</view>	 -->
					<view class="time">
						库存：{{number}}
					</view>	
					<view class="name">
						{{message.replaceAll('^','.')}}
					</view>	
					<view class="norms" >
						<tui-list-cell :hover="false" unlined="all" class="tui-list ">
					
							<view class="other-type-box">
								<view class="row" v-for="(item, key) in list.result" :class="{hl: highKeys[key]}">
									<view class="name">
					
										{{key}}
									</view>
									<view class="mod-box">
										<view v-if="value!=undefined" class="mod" v-for="(value,index) in item" :key='index'
											@click="handleActive(key, value)"
											v-bind:class="{'yes-mod theme-boder': value.active, 'cc': !value.active && value.disabled}">
											<view class="text">
												{{ value.name.replaceAll('^','.') }}
											</view>
										</view>
					
									</view>
								</view>
							</view>
					
						</tui-list-cell>
					</view>
					<view class="norms-number" >
						<view class="tit">数量</view>
						<view class="number">
							<text class="iconfont " @tap="setNum('jian')" style="color:#888;">&#xe61b; </text>
							<input type="number" v-model="num" maxlength="8" @blur="changeNum"  >
							<text class="iconfont " @tap="setNum('jia')" style="  background: #1D86B6; color: #fff;">&#xe61c;</text>
						</view>
					</view> 
					<view class="norms-number" v-if="limitInfo.is_limit"> 
						<text>限购{{limitInfo.limit_num}}件,您已购买{{limitInfo.has_num}}件,还可购买{{limitInfo.also_num}}件  </text>
			   		</view>
					<view class="btn" @tap="addBatchCartList()">
						<view class="btn-submit">
							确认
						</view>	
					</view>	
				</view>	
				
			</view>
			
		</uni-popup>
		<!-- 购物车 -->
		<uni-popup ref="batchList" type="bottom" custom="true" >
			<view class="tip"  @tap.stop="$refs.batchList.open()"> 有0种商品不符合下单要求，<span>点击查看详细</span></view>
			<view class="batch-list-box">
				<view class="title">
					<view>已选商品 <span>运费￥{{delive_fee}}</span></view>
					<ivew @tap="$refs['delModel'].open()" class="del-box">
						<text class='iconfont'>&#xe610; </text>
						<span>删除</span>
					</ivew>
				</view>
			</view>
			
			<view  v-if="cartModelShow" class="product-list"v-for="item,index in  batchCartList">
				<!-- <view>12121,{{item.name}}</view> 出现不同门店的产品会样式错乱 -->
				<scroll-view scroll-y="true"  bindscrolltoupper="upper" bindscrolltolower="lower" bindscroll="scroll" >
				<view  v-for="(v,index1) in  item.goodslist"  class="product-box">
					<view @tap.stop="check(index,index1,v)">
						<!-- {{index1}} -->
						<text :class="v.check ? 'checked' : 'check'" class="iconfont">{{v.check ? '&#xe61e;' : '&#xe638;'}}</text>
					</view>
					<view class="content">
						<view class="img"><image :src="v.src"></image></view>
						<view class="content-item">
							<view class="title">
								{{v.name}}
							</view>
							<view class="label">
								<!-- <view class="label-item">
									{{v.batch_start_num||2}}件起批
								</view> -->
								
							</view>
							<view class="norms-number">
								<view>￥{{v.price}}</view>
								<view class="number">
									<text class="iconfont " @tap="desc(index,index1)">&#xe61b; </text>
									<input type="number" v-model="v.number" maxlength="8" disabled="true" @blur="changeCardNum($event,v.product)"  >
									<text class="iconfont " @tap="add(index,index1)" style="  background: #1D86B6; color: #fff;">&#xe61c;</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				</scroll-view>
				
			</view>
			<view v-if="product_num<=0" class="no-goods">
				
					亲！购物车空空的，快去挑选吧！
				
			</view>
			<view class="cart-list" >
				<view class="batch-box" v-if="product_num>0">
				
					<!-- <view class="tip"  @tap.stop="$refs.batchList.open()"> 有0种商品不符合下单要求，<span>点击查看详细</span></view> -->
					<view class="batch-temp">
						<view class="batch-price">
							<view class="img">
								<image :src="OSS_HOST+'img/batchCard.png'"></image>
							</view>
							<view class="item-price">
								<view class="item-price-box" @tap.stop="$refs.batchList.open()">
									<span class="price"><text class="more">￥</text>{{amount}}</span> 
									<span class="detail">明细<text class="iconfont up">&#xe620;</text></span>
								</view>
								<view class="item-price-fee">
									 配送费：<span>￥{{delive_fee}}</span>
								</view>
								<view class="number">
									共{{product_type_num}}种{{product_num}}个商品
								</view>
							</view>
							<!-- <view class="num">
								1
							</view> -->
							
						</view>
						<view class="btn">
							<view class='btn-submit' @tap = "pay()">去结算</view>
							
						</view>
						
					</view>
					
				</view>
			</view>
			
			
		</uni-popup>
		<!-- 删除购物车商品 -->
		<uni-popup ref="delModel" type="center" custom="true" >
			<view class="del-tab">
				<view class="content">
					确认清除商品！
				</view>
				<view class="btn">
					<view class="btn-border" @tap="$refs['delModel'].close()">取消</view>
					<view class="btn-border btn-queren" @tap="del">确认</view>
					
				</view>
			</view>	
			
		</uni-popup>
		<!-- 登录弹框 -->
		<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />
	</view>
</template>

<script>
	// import TabBar from '../../components/TabBar/TabBar.vue';
	import store from '@/store/index.js';
	import {oss_host} from '@/config/config.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import { mapGetters } from 'vuex';
	import cart from '@/utils/cartshop.js' ;
	import Vue from 'vue'
	export default {
		components:{
			// TabBar,
			uniPopup,
			// Vue
		},
		// watch:{
		// 	batchCartList:{
		// 		handler(newGoodslist,oldval){
					
		// 			let num = 0
		// 			let product_number = 0
		// 			let amount = 0
		// 			// 格式问题无法使用foreach
		// 			for(let key in newGoodslist){
		// 				// this.cartList[key].check = _this.batchCartList[key].check
		// 				for(let key1 in newGoodslist[key].goodslist){
		// 					amount += (newGoodslist[key].goodslist[key1].price*newGoodslist[key].goodslist[key1].number)				
		// 					product_number +=newGoodslist[key].goodslist[key1].number
		// 					num  +=1
		// 					newGoodslist[key].goodslist[key1].check = true
		// 				}
		// 			}
					
		// 			this.amount=amount.toFixed(2) //累计金额
		// 			this.product_type_num=num//种类数量
		// 			this.product_num=product_number//产品数量
					
					
					
		// 			console.log('watch payCartList change')
		// 			// this.payAmount = 0
		// 			// for(let key in newGoodslist){
		// 			// 	this.cartList[key].check = newGoodslist[key].check
		// 			// 	for(let key1 in newGoodslist[key].goodslist){
		// 			// 		this.payAmount += (newGoodslist[key].goodslist[key1].price*newGoodslist[key].goodslist[key1].number)				
		// 			// 		this.cartList[key].goodslist[key1].check = true
		// 			// 	}
		// 			// }
		// 		}
		// 	},
		// 	immediate:true,
		// 	deep:true
		// },
		computed: {
			//注册网络状态
			...mapGetters(['netWorkType','loginStatus'])	
			// 一个计算属性的 getter
			
		},
		data() {
			return {
				OSS_HOST: oss_host,
				height: 0,
				property_id:0,
				property_value_id:0,
				checkIndex:0,
				search_name:'',
				is_history:false,
				detail:{},//临时存储的产品数据  
				data:{
					property:[],
					page:0,
					lastPage:0,
					productList:[],
					normsList:[],
					normsValue:[],
					activity:[],//活动类目
					
				},
				batchCartList:{},
				cartModelShow:false,
				// 规格属性
				product_norms_value_id:'',
				checkIndex:0,
				price:0,
				norms_value_id: "", //normsValue规格的id  不是sku的id
				norms_value_name:'',
				normsName: "norms_value_id",
				keys: [],
				// 数据集合{list.result list.items}
				list: {},
				// 分隔符
				spliter: '\u2299',
				result: {},
				message: "",
				highKeys: {},
				// 其他属性储存数组
				sel: [],
				sku: [],
				norms_cover_image:'',
				cost:'',
				num:1,//购买数量
				number:0,//规格动态库存
				cover_image:'',//规格图
				
				// 
				amount:0,//累计金额
				product_type_num:0,//种类数量
				product_num:0,//产品数量
				delive_fee:0,//运费
				shapeCode:'',//条码
				activity_index:'',
				ce:0,
				limitInfo:[],
				
			};
		},
		onReady() {
			// setTimeout(()=>{
			//   uni.hideTabBar()  
			// },100)
			let info = uni.createSelectorQuery().select(".page");
	　　　  info.boundingClientRect((data) => { //data - 各种参数
						console.log(data.height);
						this.height = data.height - 250;
					  // #ifdef APP-PLUS 
						this.height = data.height - 280;
						// #endif 
						
	　　    }).exec()
		},
		onShow(){
			let _this = this
			// console.log(1111)
			this.batchCartList = uni.getStorageSync('batchCartList')==''?{}:JSON.parse(uni.getStorageSync('batchCartList'))
			console.log(this.batchCartList)	
			_this.count()
		},
		onLoad: function(e)  {
			let _this = this
			// console.log(1111)
			// this.batchCartList = uni.getStorageSync('batchCartList')==''?{}:JSON.parse(uni.getStorageSync('batchCartList'))
			// console.log(this.batchCartList)	
			// _this.count()
			
			_this.getList()
		},
		onReachBottom(){
			 // 分页 上拉加载
			 // console.log(this.data.page,this.data.lastPage)
			if (this.data.page >= this.data.lastPage) {
				// console.log(1111111)
				uni.showToast({
					icon: 'none',
					title: '没有更多数据'
				});
				return;
			}
		  
		  this.getProduct();
		  
		},
		
		methods:{
			/**
			 * 扫一扫点击
			 */
			onCode(){
				let _this = this
				// 只允许通过相机扫码
				uni.scanCode({
					onlyFromCamera: true,
					success: function (res) {
							console.log('条码类型：' + res.scanType);
							console.log('条码内容：' + res.result);
							// 二维码
							if(res.scanType=='QR_CODE'){
								const code = res.result
								// _this.$service.
								
							}else{
								_this.shapeCode = '6970281570308'// res.result
								_this.data.page=0
								_this.search_name=''
								
								_this.getProduct()
							}
					},
					fail(res) {
							console.log(res)
							uni.showToast({
								icon:'none',
								title:'无法获取到扫描信息！'
							})
					}
				});
			},
			/**
			 * 搜索点击
			 */
			onSearch(){
				let _this = this
				// console.log(12121)
				_this.data.page=0
				console.log(_this.data.page); 
				_this.getProduct()
				// uni.navigateTo({url:'/pages/search/search'})
			},
			/**
			 * 付款码点击
			 */
			onPayCode(){
				uni.navigateTo({
					url: '/pages/PaymentCode/PaymentCode'
				})
			},
			// 合计
			count(){
				// console.log(112132123123123)
				let _this= this
				let num = 0
				let product_number = 0
				let amount = 0
				// 格式问题无法使用foreach
				for(let key in _this.batchCartList){
					// this.cartList[key].check = _this.batchCartList[key].check
					for(let key1 in _this.batchCartList[key].goodslist){
						amount += (_this.batchCartList[key].goodslist[key1].price*_this.batchCartList[key].goodslist[key1].number)				
						product_number += _this.batchCartList[key].goodslist[key1].number
						num  +=1
						 // _this.batchCartList[key].goodslist[key1].number
						_this.batchCartList[key].goodslist[key1].check = true
					}
				}
				
				this.amount=amount.toFixed(2) //累计金额
				this.product_type_num=num//种类数量
				this.product_num=product_number//产品数量
				// delive_fee:0,//运费
			},
			// 扫码
			scanCode(){
				let _this = this;
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						console.log(res) 
						//二维码
						if(res.scanType=='QR_CODE'){ 
							const code = res.result
							
						}else{
							// 条码
							const code = res.result
							// _this.$refer.setVilit('/pages/GoodsDetails/GoodsDetails')
							// let callback = function(url) {
							// 	_this.$refs.popupvLogin.open()
							// }
							// var data = {
							// 	code: code
							// }
							// _this.$refer.toUrl(callback, data)
						} 
						
					}
				});
			},
			getList() {
				const _this = this
					 
				var opt = {
					url: '/product/getProperty', 
					data:{
						property_id:this.property_id||'',
						
					},
					success: function(res) { 
					 
						if (res.status == 1) { 
							 let result = res.data
							
							_this.data.property =Object.values(result.list) 
							_this.property_id =_this.data.property[0]['id'] 
							_this.property_value_id = _this.data.property[0]['sub'][0]['id'] 
							// console.log('*****1',_this.data.property);
							// for(let v in _this.data.property){
							// 	_this.property_id = v.id
							// 	return
							// }
							// console.log('***** id:',_this.property_value_id);
							
							 // _this.data.property.forEach(function(item,index){
								//  _this.property_id = item.id
								//  return
							 // })
							
							
							_this.getProduct()
							
							
						}  
						// _this.skeletonShow = false;
					}
				};
			
				
				this.$service.GetApi(opt) //网络
				
			
			
			},
			getProduct(){
				const _this = this
				let data ={}
				let property_id =this.property_value_id;
				if(_this.is_history || _this.shapeCode!='' || _this.search_name !=''){
					property_id = ''
				}
				console.log(_this.data.page); 
				if(_this.is_history ){
					// 历史记录
					data ={
						property_id:property_id,
						page:++_this.data.page,
						searchName:this.search_name,
						is_history:_this.is_history,
						shape_code:_this.shapeCode||'',
						
					}
				}else{
					data= {
						property_id:property_id||'',
						page:++_this.data.page,
						searchName:this.search_name|| '',
						shape_code:_this.shapeCode||'',
						activity_id:_this.activity_index||''
					}
				} 
				var opt = {
					url: '/product/getBatchList', 
					data:data,
					success: function(res) { 
						_this.shapeCode=''
						if (res.status == 1) { 
							 let result = res.data
							
							_this.data.page=res.data.page
							_this.data.lastPage = res.data.last_page 

							if(res.data.list.length == 0){
								_this.data.page = 0;
								_this.data.productList = [];
							}else{ 
								if(res.data.page ==1){
									_this.data.productList=res.data.list
								}else{
									_this.data.productList=_this.data.productList.concat(res.data.list)
								}
							}
							// console.log('***8888',_this.data.productList)
							// 活动类目
							_this.data.activity = res.data.activty
							console.log(res)
							console.log(_this.data.activity)
							_this.$forceUpdate()
							_this.count()
						}  
						// _this.skeletonShow = false;
					}
				};
							
				
				this.$service.GetApi(opt) //网络
			},
			searchHistory(){
				this.data.page=0
				this.is_history = !this.is_history
				this.getProduct()
			},
			// 左侧分类点击
			checkProperty(item,index){
				this.property_id = item.id;
				this.checkIndex = index;
				this.property_value_id = item.sub[0]['id']|| 0;
				this.data.page =0;
				this.getProduct();
			},
			// 右侧分类
			checkPropertyValue(id){
				// 跳转
				this.property_value_id = id
				this.activity_index = ''
				this.data.page =0
				this.getProduct()
				// let _this = this
				
				// _this.$refer.setVilit('/pages/SearchGoodsList/SearchGoodsList')
				// let callback = function(url) {
				// 	_this.$refs.popupvLogin.open()
				// }
				// let data = {
				// 	property_id:id,
				// 	// a:2
				// }
				// _this.$refer.toUrl(callback, data)
			},
			checkActivity(item,index){
				// 爆款
				console.log('baok',item)
				let _this =this
				 _this.property_value_id = '',
				_this.activity_index = index.toString()
				// _this.productIds = item.values
				_this.data.page =0
				console.log(_this.activity_index,'**********')
				_this.getProduct()
				
				
			},
			toDetail(item){
				let _this = this
				_this.$refer.setVilit('/packageBatch/pages/GoodsDetails/GoodsDetails')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				let data = {
					id:item.id,
					// a:2
				}
				_this.$refer.toUrl(callback, data)
			},
			
			// 点击选择规格
			checkNorms(item){
				const _this = this
				_this.detail = item
				if(!_this.loginStatus){
					_this.$refs.popupvLogin.open()
					return;
				}
				var opt = {
					url: '/product/getNorms', 
					data:{
						id:item.id
					},
					success: function(res) { 
						
						if (res.status == 1) { 
							 let result = res.data
							_this.data.normsList= result.normsList
							_this.data.normsValue = result.normsValue
							// _this.list={}
							_this.product_norms_value_id=''
							_this.checkIndex=0
							_this.price=0
							_this.norms_value_id= "" //normsValue规格的id  不是sku的id
							_this.norms_value_name=''
							// _this.normsName= "norms_value_id"
							_this.keys=[]
             				_this.initData()
							_this.$refs.checkVenue.open()
							// _this.$forceUpdate()
							
							console.log(111)
							// console.log('****list',_this.list)
							
						}  
						// _this.skeletonShow = false;
					}
				};
							
				
				this.$service.GetApi(opt) //网络
			},
			//数量
			setNum(type){
				switch(type){
					case 'jia':
						this.num = this.num+1
						if(this.num >this.number){
							this.num = this.number
						}
					break
					case 'jian':
						this.num = this.num-1
						if(this.num<1){
							this.num =1
						}
					break
					
				}
				this.changeNum();
			},
			
			// 更改数量
			changeNum(e){
				this.num = parseInt(this.num)
				if(!this.num){
					this.num =1
				}
				if(this.num<1){
					this.num =1
				}
				if(this.num >this.number){
					this.num = this.number
				}
				console.log(this.limitInfo);
		
				if(this.limitInfo.is_limit && this.limitInfo.also_num < this.num){
					this.num =this.limitInfo.also_num
					uni.showToast({
						icon:'none',
						title:'限购'+this.limitInfo.limit_num+'件您已购买'+this.limitInfo.has_num+'件，还能购买'+this.limitInfo.also_num+'件'
					})
				}
				
			},
			showCard(){
				this.$refs.batchList.open()
				this.$nextTick(()=>{this.cartModelShow=true})
			},
			addBatchCartList(){
				let _this = this
				let goods2 = {
					product_id:this.detail.id,
					norms_value_id:this.product_norms_value_id,
					store_id:this.detail.store_id,
					store_name:this.detail.store_name,
					product_name:this.detail.name,
					norms_name:this.data.normsValue[this.norms_value_id].norms_name,
					price:this.price,//这里的价格已经在PHP 改成了批发价
					number:this.num,
					src:this.detail.cover_image,
					check:true
				}
				
				if(this.batchCartList[goods2.store_id]?.goodslist[goods2.norms_value_id] && this.limitInfo.limit_num > 0){  
					let cartnumber = this.batchCartList[goods2.store_id].goodslist[goods2.norms_value_id].number;
					if(cartnumber+this.num > this.limitInfo.limit_num){
						this.batchCartList[goods2.store_id].goodslist[goods2.norms_value_id].number = this.limitInfo.limit_num-this.num;
					}
				}
				// console.log('goods',goods2)
				  cart.add(goods2,this.batchCartList,(res)=>{
				     // console.log('res',res)
					 // res.data.cartList.forEach((item)=>{
						// console.log(item,'11111')
					 // })
					 //  list.forEach(function(v,index){ 
					 // 	Vue.set(this.list.result,index,v)
					 // })
				     uni.setStorageSync('batchCartList',JSON.stringify(res.data.cartList))
					// _this.batchCartList = res.data.cartList
					 _this.batchCartList =uni.getStorageSync('batchCartList')==''?{}:JSON.parse(uni.getStorageSync('batchCartList'))
					 	  _this.count()		
					this.cartModelShow=false
					this.$nextTick(()=>{this.cartModelShow=true})
					 // _this.$forceUpdate()
				   });
				   //  遇到for循环push对象得到新数组的情况时，应该在push里面写对象，
				   // 不应该先对对象赋值再push，
				   // 否则点击时会导致得到新数组中的所有对象的全是最后一个对象的值。
				   // 暂时 没有解决 捞点 刷新页面 重加载页面数据 
				  // uni.redirectTo({url: '/packageBatch/pages/Batch/Batch'})
				   
				 console.log(this.batchCartList,'*********')
					
				  _this.$refs.checkVenue.close()
				  
				  
			},
			//单选商品
			check(storeKey,goodsKey){
					
					console.log(this.batchCartList,'batchCartList*******')
					console.log(storeKey,'------',goodsKey)
					  let _this = this
					  // 固定数据
					   this.batchCartList[storeKey].check = true
					   
					  this.batchCartList[storeKey].goodslist[goodsKey].check = !this.batchCartList[storeKey].goodslist[goodsKey].check 
					  // this.payCartList = uni.getStorageSync('payCartList')==''?{}:JSON.parse(uni.getStorageSync('payCartList'))
					  if(this.batchCartList[storeKey].goodslist[goodsKey].check)
					  {
						  let sign = true
						  for(let key in this.batchCartList[storeKey].goodslist){
							
							if(this.batchCartList[storeKey].goodslist[key].check == false){
								this.batchCartList[storeKey].check = false
								sign = false
								break;
							}
						  	  
						  }
						  
						  if(sign)
						  {
							  this.batchCartList[storeKey].check = true
						  }
						  // //新增至预购
						  // let goods = {
						  // 	product_id:this.batchCartList[storeKey].goodslist[goodsKey].product_id,
						  // 	norms_value_id:goodsKey,
						  // 	store_id:storeKey,
						  // 	store_name:this.batchCartList[storeKey].name,
						  // 	product_name:this.batchCartList[storeKey].goodslist[goodsKey].name,
						  // 	norms_name:this.batchCartList[storeKey].goodslist[goodsKey].norms_name,
						  // 	price:this.batchCartList[storeKey].goodslist[goodsKey].price,
						  // 	number:this.batchCartList[storeKey].goodslist[goodsKey].number,
						  // 	src:this.batchCartList[storeKey].goodslist[goodsKey].src
						  // 	}
						  					
						  // cart.add(goods,_this.payCartList,(res)=>{
							 //  if(this.batchCartList[storeKey].check)
							 //  {
								// res.data.cartList[storeKey].check = this.batchCartList[storeKey].check 
							 //  }
										
						  // 	uni.setStorageSync('payCartList',JSON.stringify(res.data.cartList))
						  // 	_this.payCartList = res.data.cartList
						  // });
						  
					  }else{
						  this.batchCartList[storeKey].check = false
						  //删除预选
						  // let goods = {norms_value_id:goodsKey,store_id:storeKey}  
						
						  // cart.delProd(goods,_this.payCartList,(res)=>{
							 //  // console.log(res)
							 //  if(JSON.stringify(res.data.cartList) !=='{}'&&res.data.cartList[storeKey] instanceof Object)
							 //  {
								//   res.data.cartList[storeKey].check = false
							 //  }
								
							  
						  // 	uni.setStorageSync('payCartList',JSON.stringify(res.data.cartList))
						  // 	_this.payCartList = res.data.cartList
						  // });
					  }
					  // this.batchCartList=JSON.parse(JSON.stringify(this.batchCartList))
					  this.$forceUpdate()
					  console.log('check单选:',this.batchCartList)
			},
			
			//删除购物车商品
			  del(){
					
					   let _this = this
					  
					   
					   let batchCartList = _this.batchCartList
					    for(let storeKey in batchCartList)
						{
							for(let goodsKey in  batchCartList[storeKey].goodslist)
							{
								//删除购物车商品
								let goods = {norms_value_id:goodsKey,store_id:storeKey}  
								if( batchCartList[storeKey].goodslist[goodsKey].check){
									cart.delProd(goods,_this.batchCartList,function(res){
										uni.setStorageSync('batchCartList',JSON.stringify(res.data.cartList))
										_this.batchCartList = res.data.cartList
									});
								}
								
							}
						}	
						this.count()
						// uni.setStorageSync('batchCartList',JSON.stringify({}))
						// this.batchCartList = {}
						this.$refs['delModel'].close()
						
			  },
			  
			  add(storeKey,goodsKey){
					   let _this = this
					   //新增至预购
					   let goods = {
							product_id:this.batchCartList[storeKey].goodslist[goodsKey].product_id,
							norms_value_id:goodsKey,
							store_id:storeKey,
							store_name:this.batchCartList[storeKey].name,
							product_name:this.batchCartList[storeKey].goodslist[goodsKey].name,
							norms_name:this.batchCartList[storeKey].goodslist[goodsKey].norms_name,
							price:this.batchCartList[storeKey].goodslist[goodsKey].price,
							number:1,
							src:this.batchCartList[storeKey].goodslist[goodsKey].src
					   	}
					   	// if(_this.batchCartList[storeKey].goodslist[goodsKey].check)
					   	// {
					   	// 			   cart.add(goods,_this.payCartList,(res)=>{
					   	// 				uni.setStorageSync('payCartList',JSON.stringify(res.data.cartList))
										
					   	// 				_this.payCartList = JSON.parse(JSON.stringify(res.data.cartList))
										
					   	// 			   });
					   	// }				 
					   cart.add(goods,_this.batchCartList,(res)=>{
							_this.batchCartList = JSON.parse(JSON.stringify(res.data.cartList))
							// Vue.set(_this.cartList[storeKey].goodslist[goodsKey],'number',res.data.cartList[storeKey].goodslist[goodsKey].number)
							for(let key in res.data.cartList)
							{
								res.data.batchCartList[key].check =false
								for(let key1 in res.data.cartList[key].goodslist)
								{
									res.data.cartList[key].goodslist[key1].check =false
								}
								
							}
							uni.setStorageSync('batchCartList',JSON.stringify(res.data.cartList))
							
							
					   });
					   this.count()
					   // console.log('add111 cartList',_this.cartList)
					   //  console.log('add222 payCartList',_this.payCartList)
						this.$forceUpdate() 
			  },
			  desc(storeKey,goodsKey){
					   let _this = this
					   let goods = {norms_value_id:goodsKey,store_id:storeKey}
					   	
						// if(_this.batchCartList[storeKey].goodslist[goodsKey].check)
						// {
						// 	cart.desc(goods,_this.payCartList,function(res){
						// 					uni.setStorageSync('payCartList',JSON.stringify(res.data.cartList))
						// 					_this.payCartList = JSON.parse(JSON.stringify(res.data.cartList))
						// 	});
						// }
								
					   cart.desc(goods,_this.batchCartList,function(res){
						   _this.batchCartList = JSON.parse(JSON.stringify(res.data.cartList))
						   for(let key in res.data.cartList)
						   {
						   	res.data.cartList[key].check =false
						   	for(let key1 in res.data.cartList[key].goodslist)
						   	{
						   		res.data.cartList[key].goodslist[key1].check =false
						   	}
						   	
						   }
							uni.setStorageSync('batchCartList',JSON.stringify(res.data.cartList))
							
							
					   });
						
						
						this.count()
						// console.log('desc cartList',_this.cartList)
						//  console.log('desc payCartList',_this.payCartList)
						 this.$forceUpdate()  
			  },
			
			pay(){
					 let _this = this
					 
						console.log(this.payCartList)
					   if(JSON.stringify(this.batchCartList)==='{}')
					   {
						   // console.log('请选择商品')
						   uni.showToast({
						   	icon:'error',
							title:'请选择商品'
						   })
						   return
					   }
					   
					   console.log('支付')
					   // product:'[{"id":"67","norms_value_id":97,"num":1},{"id":"69","norms_value_id":99,"num":2}]'
					   let goodsRequest = {product:[]}
					   for(let key in this.batchCartList)
					   {
					   	
					   	for(let key1 in this.batchCartList[key].goodslist)
					   	{
					   		let goods = {
											id:this.batchCartList[key].goodslist[key1].product_id,
											norms_value_id:key1,
											num:this.batchCartList[key].goodslist[key1].number,
											store_id:this.batchCartList[key].goodslist[key1].store_id,
											product_id:this.batchCartList[key].goodslist[key1].product_id,
											product_name:this.batchCartList[key].goodslist[key1].name,
											price:this.batchCartList[key].goodslist[key1].price,
											cover_image:this.batchCartList[key].goodslist[key1].src,
										}
										
							goodsRequest.product.push(goods)	
					   	}
					   	
					   }
					   _this.$refer.setVilit('/pages/PayOrder/submit_order')
					   let callback = function(url) {
					   	_this.$refs.popupvLogin.open()
					   }
					   let data = {
						   type:'batchCart',
						   related_type:'batch',
							product:JSON.stringify(goodsRequest.product),
						
					   }
					   _this.$refer.toUrl(callback, data)
					   // console.log(goodsRequest)
			},
			
			// 多规格选择 start
			/**
			 * 初始化数据
			 * @return
			 */
			initData() {
				// this.data = JSON.parse(data);
				let isHas = false;
				let norms_value_id = 0
				for (let i = 0; i < this.data.normsList.length; i++) {
					if (norms_value_id == this.data.normsList[i][this.normsName]) {
						isHas = true;
						break
					}
				}
				this.norms_value_id = isHas ? norms_value_id : this.data.normsList[0][this.normsName];
				// console.log(1111)
				// console.log(this.norms_value_id)
				this.result = {};
				this.keys = this.getAllKeys();
				// console.log('key****',this.keys)
				for (let i = 0; i < this.keys.length; i++) {
					this.highKeys[this.keys[i]] = false;
				}
			
			
				let list = this.combineAttr(this.data.normsList, this.keys);
		
				// list.forEach(function(v,index){
				// 	Vue.set(this.list.result,index,v)
				// })
				// for(let v, list){
					
				// }
				Vue.set(this.list, 'items', list.items)
				// console.log('77777777777',this.list)
				// let i=this.ce
				// this.ce = i+1;
				//  let name='测试'+i;
				// Vue.set(this.list, 'result', {
				// 	'规格':{
				// 		name:{
				// 			active: true,
				// 			disabled: true,
				// 			name: name,
				// 			},
				// 		},
				// 	})
					
					Vue.set(this.list, 'result',list.result)

				
				
				
				// let name='测试'+i;
				
				
				// this.list ={'items':{},
				// 'result':{
				// 	'规格':{
				// 		name:{
				// 			active: true,
				// 			disabled: true,
				// 			name: name,
				// 			},
				// 		},
				// 	},
				// }

				//console.log(this.list.items)
				this.initSeleted(this.norms_value_id);
				this.buildResult(this.list.items)
				this.updateStatus(this.getSelectedItem());
				this.showResult();
			},
			/**
			 * 正常属性点击
			 */
			handleNormalClick(key, value) {
				for (let i in this.list.result[key]) {
					if (i != value.name) {
						this.list.result[key][i].active = false;
					} else {
						this.list.result[key][i].active = true;
					}
				}
			},
			
			/**
			 * 无效属性点击
			 */
			handleDisableClick(key, value) {
				this.list.result[key][value.name]["disabled"] = false;
				// 清空高亮行的已选属性状态（因为更新的时候默认会跳过已选状态）
				for (let i in this.list.result) {
					if (i != key) {
						for (let x in this.list.result[i]) {
							this.list.result[i][x].active = false;
						}
					}
				}
			
				this.updateStatus(this.getSelectedItem());
			},
			
			/**
			 * 高亮行
			 */
			highAttributes: function() {
				for (let key in this.list.result) {
					this.highKeys[key] = true;
					for (let attr in this.list.result[key]) {
						if (this.list.result[key][attr].active === true) {
							this.highKeys[key] = false;
							break;
						}
					}
				}
			},
			
			/**
			 * 点击事件处理
			 * @param  key   点击的行
			 * @param  value 点击的按钮的数据
			 */
			handleActive: function(key, value) {
				this.sel[key] = value //让数组sel的第topkey+1的元素的值等于subkey
				// console.log(1111)
				// console.log(this.sel)
				if (value.active == true) {
					return false;
				}
			
				this.handleNormalClick(key, value);
				if (value.disabled === true) {
					this.handleDisableClick(key, value);
				}
			
				this.updateStatus(this.getSelectedItem());
			
				this.highAttributes();
				this.showResult();
			},
			/**
			 * 计算属性
			 * @param  {[type]} data [description]
			 * @param  {[type]} keys [description]
			 * @return {[type]}      [description]
			 */
			combineAttr(data, keys) {
				let allKeys = []
				let result = {}
			
				for (let i = 0; i < data.length; i++) {
					let item = data[i]
					let values = []
			
					for (let j = 0; j < keys.length; j++) {
						let key = keys[j]
						if (!result[key]) {
							result[key] = {};
						}
			
						if (!result[key][item[key]]) {
							result[key][item[key]] = {
								"name": item[key],
								"active": false,
								"disabled": true
							};
						}
			
						values.push(item[key]);
					}
			
					allKeys.push({
						path: values.join(this.spliter),
						sku: item['norms_value_id']
					});
				}
				// console.log('******result:',result)
				return {
					result: result,
					items: allKeys
				}
			},
			/**
			 * 获取所有属性
			 * @return {[type]} [description]
			 */
			getAllKeys() {
				let arrKeys = [];
				// console.log(11111);
				//console.log(this.normsList);
				for (let attribute in this.data.normsList[0]) {
					if (!this.data.normsList[0].hasOwnProperty(attribute)) {
			
						continue;
					}
			
					if (attribute !== this.normsName) {
						arrKeys.push(attribute);
					}
				}
				// console.log(this.normsList[0])
				console.log(222,arrKeys)
				return arrKeys;
			},
			
			getAttruites(arr) {
				let result = []
				for (let i = 0; i < arr.length; i++) {
					result.push(arr[i].path)
				}
			
				return result
			},
			
			/**
			 * 生成所有子集是否可选、库存状态 map
			 */
			buildResult(items) {
				let allKeys = this.getAttruites(items)
			
				for (let i = 0; i < allKeys.length; i++) {
					let curr = allKeys[i];
					let sku = items[i].sku;
					let values = curr.split(this.spliter);
					let allSets = this.powerset(values);
			
					// 每个组合的子集
					for (let j = 0; j < allSets.length; j++) {
						let set = allSets[j]
						let key = set.join(this.spliter)
			
						if (this.result[key]) {
							this.result[key].skus.push(sku)
						} else {
							this.result[key] = {
								skus: [sku]
							}
						}
					}
				}
			},
			
			/**
			 * 获取选中的信息
			 * @return Array
			 */
			getSelectedItem() {
				let result = [];
				for (let attr in this.list.result) {
					let attributeName = '';
					for (let attribute in this.list.result[attr]) {
						if (this.list.result[attr][attribute].active === true) {
							attributeName = attribute;
						}
					}
			
					result.push(attributeName);
				}
				// console.log(2222)
				// consle.log(result)
				return result
			},
			
			/**
			 * 更新所有属性状态
			 */
			updateStatus(selected) {
				for (let i = 0; i < this.keys.length; i++) {
					let key = this.keys[i],
						data = this.list.result[key],
						hasActive = !!selected[i],
						copy = selected.slice();
			
					for (let j in data) {
						let item = data[j]["name"];
						if (selected[i] == item) {
							continue
						}
			
						copy[i] = item
						let curr = this.trimSpliter(copy.join(this.spliter), this.spliter);
						this.list.result[key][j]["disabled"] = this.result[curr] ? false : true;
					}
				}
			},
			
			trimSpliter(str, spliter) {
				// ⊙abc⊙ => abc
				// ⊙a⊙⊙b⊙c⊙ => a⊙b⊙c
				let reLeft = new RegExp('^' + spliter + '+', 'g');
				let reRight = new RegExp(spliter + '+$', 'g');
				let reSpliter = new RegExp(spliter + '+', 'g');
				return str.replace(reLeft, '')
					.replace(reRight, '')
					.replace(reSpliter, spliter)
			},
			/**
			 * 初始化选中
			 * @param  mixed|Int|String norms_value_id 需要选中的norms_value_id
			 * @return {[type]}       [description]
			 */
			initSeleted(norms_value_id) {
				for (let i in this.data.normsList) {
					if (this.data.normsList[i][this.normsName] == norms_value_id) {
						for (let x in this.data.normsList[i]) {
							if (x !== this.normsName) {
								this.list.result[x][this.data.normsList[i][x]].active = true;
							}
						}
						break;
					}
				}
			},
			/**
			 * 显示选中的信息
			 * @return
			 */
			showResult() {
				let result = this.getSelectedItem()
				// console.log(11111)
				// console.log(result)
				let s = []
				for (let i = 0; i < result.length; i++) {
					let item = result[i];
					if (!!item) {
						s.push(item)
					}
				}
			
				if (s.length == this.keys.length) {
					let curr = this.result[s.join(this.spliter)]
					if (curr) {
						// s = s.concat(curr.skus)
						this.norms_value_id = curr.skus[0];
					}
			
					this.message = s.join('\u3000');
				}
				if (this.norms_value_id != '') {
			
					this.price = this.data.normsValue[this.norms_value_id].price
					this.norms_value_name = this.message
					this.product_norms_value_id=this.data.normsValue[this.norms_value_id].norms_id
					// console.log('*****product_norms_value_id',this.product_norms_value_id)
					// this.cover_image = this.data.normsValue[this.norms_value_id].cover_image
					this.number = this.data.normsValue[this.norms_value_id].number
					this.norms_cover_image = this.data.normsValue[this.norms_value_id].cover_image
					this.cost =  this.data.normsValue[this.norms_value_id].cost 
					this.limitInfo = this.data.normsValue[this.norms_value_id].limit_info
				}
			
			
			
			
				// console.log(this.norms_value_id)
				// console.log(this.message)
			},
			
			
			/**
			 * 获取输入表单中的数据进行初始化
			 * @return
			 */
			getTextareaData() {
				let data = document.getElementById('values').value;
				let norms_value_id = document.getElementById("norms_value_id").value;
			
				try {
					this.data = JSON.parse(data);
					let isHas = false;
					for (let i = 0; i < this.data.length; i++) {
						if (norms_value_id == this.data[i][this.normsName]) {
							isHas = true;
							break
						}
					}
			
					this.norms_value_id = isHas ? norms_value_id : this.data[0][this.normsName];
					this.initData();
				} catch (e) {
					this.data = [];
				}
			},
			powerset(arr) {
				let ps = [
					[]
				];
				for (let i = 0; i < arr.length; i++) {
					for (let j = 0, len = ps.length; j < len; j++) {
						ps.push(ps[j].concat(arr[i]));
					}
				}
			
				return ps;
			},
			// 多规格选择 end
			
			
			
			
		}
	}
</script>

<style scoped lang="scss">
@import 'Batch.scss'
</style>
